import { defineStore } from 'pinia'
import { 
  followUser, unfollowUser, unfollowAllByFollower, 
  unfollowAllByFollowed, isFollowing, 
  getFollowingCount, getFollowersCount, 
  getFollowingList, getFollowersList 
} from '@/api/follows'

export const useFollowStore = defineStore('follows', {
  state: () => ({
    following: [],
    followers: [],
    isLoading: false,
    error: null
  }),
  actions: {
    async followUser(followerId, followedId) {
      this.isLoading = true
      this.error = null
      try {
        await followUser(followerId, followedId)
        return true
      } catch (error) {
        this.error = error.message || '关注失败'
        return false
      } finally {
        this.isLoading = false
      }
    },
    
    async unfollowUser(followerId, followedId) {
      this.isLoading = true
      this.error = null
      try {
        await unfollowUser(followerId, followedId)
        return true
      } catch (error) {
        this.error = error.message || '取消关注失败'
        return false
      } finally {
        this.isLoading = false
      }
    },
    
    async checkIsFollowing(followerId, followedId) {
      this.isLoading = true
      this.error = null
      try {
        const following = await isFollowing(followerId, followedId)
        return following
      } catch (error) {
        this.error = error.message || '检查关注状态失败'
        return false
      } finally {
        this.isLoading = false
      }
    },
    
    async fetchFollowingCount(followerId) {
      this.isLoading = true
      this.error = null
      try {
        const count = await getFollowingCount(followerId)
        return count
      } catch (error) {
        this.error = error.message || '获取关注数失败'
        return 0
      } finally {
        this.isLoading = false
      }
    },
    
    async fetchFollowersCount(followedId) {
      this.isLoading = true
      this.error = null
      try {
        const count = await getFollowersCount(followedId)
        return count
      } catch (error) {
        this.error = error.message || '获取粉丝数失败'
        return 0
      } finally {
        this.isLoading = false
      }
    },
    
    async fetchFollowingList(followerId) {
      this.isLoading = true
      this.error = null
      try {
        const followingList = await getFollowingList(followerId)
        this.following = followingList
        return followingList
      } catch (error) {
        this.error = error.message || '获取关注列表失败'
        return []
      } finally {
        this.isLoading = false
      }
    },
    
    async fetchFollowersList(followedId) {
      this.isLoading = true
      this.error = null
      try {
        const followersList = await getFollowersList(followedId)
        this.followers = followersList
        return followersList
      } catch (error) {
        this.error = error.message || '获取粉丝列表失败'
        return []
      } finally {
        this.isLoading = false
      }
    }
  }
})